import web
render = web.template.render('templates/')

urls = (
    '/','index',
    '/add','add',
    '/_list/(\d+)','list',
    '/(.*)','page',
    )

class index:
    '''Displays a simple textfield to get the page name as input.'''
    
    def GET(self):
        snips = web.db.select('snips')
        print render.index(snips)

class add:
    '''Adds a new page to the database.'''
    
    def POST(self):
        i = web.input()
        n = web.insert('snips', title=i.title, text=i.text)
        web.seeother('./%s' %i.title)

class page:
    '''Displays the page contents with a editable text area to save changes. '''
    def GET(self, title):
        pg=web.db.select('snips', where="title=\'%s\'" %title)
        try:
            i=[]
            for value in pg:  # dirty hack to convert iterator to list
                i.append(value)
            print render.page(i)
        except IndexError:
            print render.new(title)

    def POST(self, title):
        i = web.input()
        if i.text == '':
            web.db.delete('snips', where='id=%s' %i.id)
            web.redirect('/')
        else:
            n = web.db.update('snips', int(i.id), text=i.text)
            web.redirect('./'+title)

class list:
    '''Lists all the snips in the database.'''
    def GET(self,pageno):
        snips = web.db.select('snips', limit=100, offset=(int(pageno)-1)*100)
        print render.list(snips)

web.config.db_parameters = dict(dbn='mysql', user='root', pw='', db='snip')
web.webapi.internalerror = web.debugerror

if __name__ == "__main__":
    web.run(urls, globals(), web.reloader)

            
